package protoctl

import (
	"errors"
	"fmt"
	"net"

	"gitee.com/lcc_dr/restful-api-demo/apps"
	"gitee.com/lcc_dr/restful-api-demo/conf"
	"github.com/infraboard/mcube/logger"
	"github.com/infraboard/mcube/logger/zap"
	"google.golang.org/grpc"
)

type GrpcServer struct {
	srv *grpc.Server
	log logger.Logger
}

func (h *GrpcServer) Start() error {

	addr := fmt.Sprintf("%s:1%s", conf.GetConf().App.Host, conf.GetConf().App.Port)
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		panic(err)
	}
	h.log.Infof("start GrpcServer listenAndServe is %s", addr)
	if err := h.srv.Serve(listener); err != nil {

		if errors.Is(err, grpc.ErrServerStopped) {
			h.log.Info("stop GrpcServer Success")

		} else {
			h.log.Errorf("Failed to listen and GrpcServer,error: %v", err)

			return err

		}

	}
	return nil
}

func (h *GrpcServer) Stop() error {

	h.log.Info("GrpcServer exiting")

	h.srv.GracefulStop()

	return nil

}

func NewGrpcServer() *GrpcServer {

	grpc := grpc.NewServer()
	apps.InitGrpc(grpc)
	return &GrpcServer{
		srv: grpc,
		log: zap.L().Named("grpc-Server"),
	}
}
